package com.kung.qvs.ui.main;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;

import com.jackiepenghe.serialportlibrary.OnSerialPortDataChangedListener;
import com.jackiepenghe.serialportlibrary.SerialPortManager;
import com.kung.qvs.BR;
import com.kung.qvs.R;
import com.kung.qvs.app.AppApplication;
import com.kung.qvs.app.AppViewModelFactory;
import com.kung.qvs.databinding.ActivityHomeWorkerBinding;
import com.kung.qvs.utils.HexUtil;
import com.kung.qvs.utils.SerialManagerCard;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;

import me.goldze.mvvmhabit.base.BaseActivity;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class HomeWorkerActivity extends BaseActivity<ActivityHomeWorkerBinding, HomeWorkerModel> {
    private static String TAG = "HomeWorkerActivity";
    public static HomeWorkerActivity mHomeActivity;
    public static KungViewModel kungViewModel;

    private ConnectedThread mConnectedThread;

    Timer timer = new Timer(true);
    public static final int REC_DATA = 2;

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_home_worker;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public HomeWorkerModel initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(HomeWorkerModel.class);
    }

    @Override
    public void initData() {
        super.initData();
        AppApplication.homeWorkerActivity = new WeakReference<HomeWorkerActivity>(this);
        mHomeActivity = this;

        kungViewModel = new ViewModelProvider(this).get(KungViewModel.class);

        try {
            openSerialCardRead();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

//        aotoConnectReadCardDevice();

        SerialPortManager.setOnSerialPortDataChangedListener(new OnSerialPortDataChangedListener() {
            @Override
            public void serialPortDataReceived(byte[] data, int size) {
                //将接收到的数据转换成16进制字符串
//                String temp_data = HexUtil.formatHexString(data, false).toUpperCase();
                //转换为字符串
                if (data.length ==22) {
                    byte[] temp = Arrays.copyOfRange(data, 5, 10);
                    String temp_data = new String(temp);
                    //解析读取到的数据
                    kungViewModel.setmSearchWorkerCode(temp_data);
                    //根据卡号查询工人信息
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            timer.cancel();
            SerialPortManager.closeSerialPort();
            if (SerialManagerCard.getInstance().isOpened()) {
                SerialManagerCard.getInstance().closeSerial();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 连接串口读卡器
     */
    public void openSerialCardRead() throws IOException {
//        if (!new File("/dev/ttyS2").exists()) {
//            ToastUtils.showShort("串口不存在!");
//            return;
//        } else {
//            ToastUtils.showShort("串口存在!");
//        }
//        serialttyS2 = new SerialPort("S2", 115200, 8, 1, 0);//打印
//        Log.e("serialtty打印机", serialttyS2.toString());
//        if (serialttyS2 == null) {
//            ToastUtils.showShort("串口初始化异常!");
//        }

        if (SerialPortManager.isOpened()) {
            ToastUtils.showShort("串口已打开!");
            return;
        }
        boolean open = SerialPortManager.openSerialPort("/dev/ttyS2", 9600);
        if (open) {
            ToastUtils.showShort("串口打开成功!");
        } else {
            ToastUtils.showShort("串口打开失败!");
        }
    }


    /**
     * 自动连接蓝牙任务
     */
    private void aotoConnectReadCardDevice() {
        //定时任务，连接蓝牙秤
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                if (!SerialManagerCard.getInstance().isOpened()) {
                    SerialManagerCard.getInstance().openSerial("/dev/ttyS2", 9600);
                    // 开启已连接线程
                    if (mConnectedThread == null) {
                        mConnectedThread = new ConnectedThread(SerialManagerCard.getInstance().getSerialPort());
                        mConnectedThread.start();
                    }
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            ToastUtils.showShort("串口打开成功");
//                        }
//                    });
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtils.showShort("串口打开失败");
                        }
                    });

                }
            }
        },100,2000);
    }

    // 用于从线程获取信息的Handler对象
    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler(){
        String msgResult;
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case REC_DATA:
                    try{
                        msgResult = (String) msg.obj;
                        //读取到的数据
                        kungViewModel.setmSearchWorkerCode(msgResult);
//                        doDealDecryptionWeight(msgResult);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };

    /**
     * 已连接的相关处理线程
     */
    private class ConnectedThread extends Thread {
        private final com.aill.androidserialport.SerialPort serialPort;
        private final InputStream mInputStream;
        private final OutputStream mOutputStream;

        public ConnectedThread(com.aill.androidserialport.SerialPort socket) {
            serialPort = socket;
            InputStream is;
            OutputStream os;
            // 获取输入输出流
            is = serialPort.getInputStream();
            os = serialPort.getOutputStream();

            mInputStream = is;
            mOutputStream = os;
        }

        public void run() {
            byte[] buffer = new byte[1024];
            DataInputStream in = new DataInputStream(mInputStream);
            // 监听输入流以备获取数据
            while (true) {

                try {
                    if (mInputStream.available() > 0) {
                        //当接收到数据时，sleep 500毫秒（sleep时间自己把握）
                        Thread.sleep(50);
                        //sleep过后，再读取数据，基本上都是完整的数据
//                        buffer = new byte[mInputStream.available()];
//                        size = mInputStream.read(buffer);
                        int l;
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        while ((l = in.read(buffer)) != -1) {
                            out.write(buffer, 0, l);
                            break;
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtils.showShort("run:接收数据");
                            }
                        });
                        //转换为16进制字符串-健坤专用，别的称可能不支持
                        String temp_data = HexUtil.formatHexString(out.toByteArray(), false).toUpperCase();
                        mHandler.obtainMessage(REC_DATA, temp_data).sendToTarget();
                    }
                } catch (IOException | InterruptedException e) {
                    Log.e(TAG, "connection break", e);
                    break;
                }
                try {
                    //线程睡眠20ms以避免过于频繁工作  50ms->20ms 2017.12.2
                    //导致UI处理发回的数据不及时而阻塞
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }
}
